# Table_A09b-A14b.R

# Part of the replication archive for 
#
#   Bullock, John G. 2020. "Education and Attitudes toward Redistribution in
#   the United States." British Journal of Political Science 50.


# This file produces Tables A9b through A14b in the appendix to the article. 
# The tables report reduced-form estimates.


source("IV_setup.R")
source("functions/getClusters.R")
outputFilenameStem <- 'float_output/Table_A09b-A14b'  


# SET UP THE REDUCED-FORM MODELS
RF_models <- eapply(IVModelsEnv, getReducedForm)  
RF_models <- addModNumAttribute(RF_models) 
RF_models <- list2env(RF_models)

# CREATE DATA FRAMES FOR ESTIMATION
GSS.df$educ1      <- GSS.df$educ2 <- GSS.df$educ5 <- GSS.df$educ6 <- GSS.df$educ
ANES.df$educ3     <- ANES.df$educ4 <- ANES.df$educ
GSS.df.eqwlth     <- GSS.df [!is.na(GSS.df$eqwlth)           & !is.na(GSS.df$educ), ]
GSS.df.goveqinc   <- GSS.df [!is.na(GSS.df$goveqinc)         & !is.na(GSS.df$educ), ]
ANES.df.guarantee <- ANES.df[!is.na(ANES.df$guarantee.7pt)   & !is.na(ANES.df$educ), ]
ANES.df.health    <- ANES.df[!is.na(ANES.df$govt.health.7pt) & !is.na(ANES.df$educ), ]
GSS.df.helppoor   <- GSS.df [!is.na(GSS.df$helppoor)         & !is.na(GSS.df$educ), ]
GSS.df.welfare    <- GSS.df [!is.na(GSS.df$welfare)          & !is.na(GSS.df$educ), ]

# ESTIMATE MODELS
dfNames  <- c(
  'GSS.df.eqwlth',  'GSS.df.goveqinc', 'ANES.df.guarantee',
  'ANES.df.health', 'GSS.df.helppoor', 'GSS.df.welfare') 
varNames <- qw('eqwlth goveqinc guarantee.7pt govt.health.7pt helppoor welfare')
RF_modelObjectsEnv <- estimateModels(
  varNames     = varNames, 
  modelEnvir   = RF_models,  
  dfNames      = dfNames,
  estFun       = lm,
  objectSuffix = '.lm') 


# CONSTRUCT CAPTIONS
varNamesLong <- c(
  'redistribution to the poor~(1)',
  'redistribution to the poor~(2)',
  'guaranteed standard of living',
  'health care',
  'help the poor',
  'welfare')
datasetNames <- gsub('.df.*', '', dfNames)
capString1   <- paste0(
  '\\textit{Reduced form: effects of compulsory schooling laws on ``',
  varNamesLong,
  '.\'\'}')
captionStrings      <- paste0(
  capString1, 
  '  Cell entries are OLS estimates and standard errors.  The four columns correspond to the four models used in \\autoref{FigIVMainResults}.  ``CA\'\' is ``compulsory attendance.\'\'  All models include controls for age, gender, race, year of interview, year in which the subject turned~14, state of residence at age~14, state of residence at time of interview, and whether the subject was born in the United States.  Standard errors are clustered at the state-year level.')
names(captionStrings) <- varNames


# MAKE ASCII TABLES
# First, create a list that contains six lists -- one for each variable.  Each  
# "inner list" contains four regression objects, corresponding to the four  
# models that were estimated for each outcome.
RF_modelObjectsList <- list()
RF_clusters         <- list() 
for (varName in varNames) {
  RF_modelObjectsList[[varName]] <- mget(
    x     = paste0(varName, '.lm', 1:length(IVModelsEnv)),
    envir = RF_modelObjectsEnv)
  RF_clusters[[varName]] <- lapply(RF_modelObjectsList[[varName]], getClusters)
}
  
# Now create a list, RF_estimates, that contains the regression tables
# (of class "regTable") themselves.  [2014 07 15]
RF_estimates   <- list()
RF_latexTables <- list() 
RF_rowNames <- c(
  'CA $\\in$ \\{ 8, 9, 10 \\}',
  'CA $\\geq$ 11'
)
RF_colNames <- list(
  c('',          '',               '',             'with'),
  c('',          'with',           'with',         'political and'),
  c('',          'cohort-year',    'state-year',   'demographic'),
  c('baseline',  'fixed effects',  'trend vars.',  'controls'))  

  
for (varName in varNames) {
  RF_estimates[[varName]] <- regTable(
    objList      = RF_modelObjectsList[[varName]],
    rowsToKeep   = "CA.fac",
    clusterSEs   = TRUE,
    clusterVar   = RF_clusters[[varName]] 
  )
  R2          <- sapply(RF_modelObjectsList[[varName]], function (x) summary(x)$r.squared )
  SER         <- sapply(RF_modelObjectsList[[varName]], function (x) summary(x)$sigma )
  N           <- sapply(RF_modelObjectsList[[varName]], nobs)
  maxResponse <- get(paste0(varName, '.lm1'), RF_modelObjectsEnv)
  maxResponse <- max(maxResponse$model[, varName])
  footerRows  <- list(
    c('$R^2$', round(R2, 2)),
    c('Standard error of regression', round(SER, 2)),
    c('Number of observations', N))  
  commandNameVarName <- gsub('.7pt', '', varName)
  RF_latexTables[[varName]] <- latexTable(
    mat                = RF_estimates[[varName]],
    decimalPlaces      = 3,
    rowNames           = RF_rowNames,
    colNames           = RF_colNames,
    hspace             = '-.3125in',
    spacerColumns      = seq(0, ncol(RF_estimates[[varName]]) - 1, by = 2),  # before rowname and after each SE column
    spacerColumnsWidth = '1.05em',    
    headerFooter       = TRUE,
    footerRows         = footerRows,
    caption            = captionStrings[[varName]],
    captionMargins     = c('.3in', '.3in'),       
    commandName        = paste0('TabReducedForm', gsub('\\.', '', commandNameVarName)),
    callCommand        = FALSE)
}

# TWEAK THE FORMATTING OF THE TABLES
tweakTables <- function (myTable) {
  myIndex <- grep('{{\\hspace*{0em}}}N', myTable, fixed = TRUE)
  myTable[myIndex[2]] <- sub(
    pattern     = '{{\\hspace*{0em}}}N{0}{3}',
    replacement = '{{\\hspace*{0em}}}N{1}{3}',
    x           = myTable[myIndex[2]],
    fixed       = TRUE)
  myTable[myIndex[4]] <- sub(
    pattern     = '{{\\hspace*{0em}}}N{0}{3}',
    replacement = '{{\\hspace*{.25em}}}N{1}{3}',
    x           = myTable[myIndex[4]],
    fixed       = TRUE)
  myTable
}
RF_latexTables <- lapply(RF_latexTables, tweakTables)


# CREATE LATEX FILE THAT CONTAINS ALL TABLES
latexTablePDF(
  latexCommands      = RF_latexTables, 
  firstPageEmpty     = FALSE,  
  continuedFloat     = TRUE,   # TRUE because RF tables follow first-stage tables in the appendix
  wrapper            = FALSE,  # FALSE if inserting LaTeX tables into appendix of my paper
  outputFilenameStem = outputFilenameStem,
  overwriteExisting  = TRUE,
  keepPDFFile        = FALSE,
  keepTexFile        = TRUE,
  openPDFOnExit      = FALSE)
